let current_rgb = ["255", "255", "255"]



//传入rgb字符串（rgb(22,33,44)） 返回CMYK对象
const RGBtoCMYK = function(rgb) {
    let CMYK = {};
    let arr = rgb.split(',');
    CMYK['r'] = parseInt(arr[0].substr(4));
    CMYK['g'] = parseInt(arr[1]);
    CMYK['b'] = parseInt(arr[2].substr(0, arr[2].length - 1));

    let r1 = CMYK['r'] / 255,
        g1 = CMYK['g'] / 255,
        b1 = CMYK['b'] / 255;

    CMYK["k"] = 1 - Math.max(r1, g1, b1);
    CMYK["c"] = Math.ceil((1 - r1 - CMYK['k']) / (1 - CMYK['k']) * 100);
    CMYK["m"] = Math.ceil((1 - g1 - CMYK['k']) / (1 - CMYK['k']) * 100);
    CMYK["y"] = Math.ceil((1 - b1 - CMYK['k']) / (1 - CMYK['k']) * 100);
    CMYK["k"] = Math.floor(CMYK['k'] * 100);

    return CMYK;
}

//更改名字和rgb值
const changeName = function(name, cx16) {
    let name_box = document.querySelector('#colorInfo .name');
    let rgb = document.querySelector('#colorInfo .rgb_cx16');
    rgb.innerHTML = cx16;
    name_box.style.opacity = 0;
    setTimeout(() => {
        name_box.innerHTML = name;
        name_box.style.opacity = 1;
    }, 1000);

}

//更改CMYK和RGB
const changeValue = function(CMYK_obj) {
    let CMYK_boxs = document.querySelectorAll("#CMYK_Value > div");
    CMYK_boxs.forEach((obj, idx) => {
        let char = CMYK_boxs[idx].className;
        let num = CMYK_obj[char];
        //改变数字
        let value_box = CMYK_boxs[idx].querySelector('.cfont');
        value_box.innerHTML = num;
        //改变圆盘刻度
        let line_l = CMYK_boxs[idx].querySelector('.l .line');
        let line_r = CMYK_boxs[idx].querySelector('.r .line');

        if (num <= 50) {
            line_r.style.transform = `rotate(${num*180/50}deg)`
            line_l.style.transform = `rotate(180deg)`
        } else {
            line_r.style.transform = `rotate(180deg)`
            line_l.style.transform = `rotate(${180+(num-50)*180/50}deg)`
        }
    })


    let { r, g, b } = { ...CMYK_obj }
    let rgb_arr = [r, g, b]
    //给数字补上0

    rgb_arr.forEach((val, idx) => {
        if (val < 10) {
            rgb_arr[idx] = "00" + val;
        } else if (val < 100 && val >= 10) {
            rgb_arr[idx] = "0" + val;
        } else {
            rgb_arr[idx] = val.toString();
        }
    })

    let RGB_box = document.querySelectorAll('.rgb_num');
    //rgb三个数字循环处理
    RGB_box.forEach((item, idx) => {
        //三个字每个字单独处理
        let current_n = current_rgb[idx].split("");
        let new_n = rgb_arr[idx].split("");
        let nums = RGB_box[idx].querySelectorAll('div');
        nums.forEach((item, idx) => {
            //92 34 35
            let step = -26.375 //转换一个数字需要位移的px

            if (idx == 0) {
                let str = `translateY(${(2-parseInt(new_n[idx]))*step}px)`
                item.style.transform = str;
            } else {
                let str = `translateY(${(9-parseInt(new_n[idx]))*step}px)`
                item.style.transform = str;
            }
        })
    })
    current_rgb = rgb_arr;

}



//传入一个对象，分别是CMYK的值
function drawCanvas(CMYK_obj, canvas) {
    let {
        c,
        m,
        y,
        k,
        r,
        g,
        b,
    } = { ...CMYK_obj };
    if (c != undefined && m != undefined && y != undefined && k != undefined) {

        // 先转换圆的度数 1 CMYK = 360/99 deg
        let roate_c = c * 360 / 99 - 90;
        let roate_m = m * 360 / 99 - 90;
        let roate_y = y * 360 / 99 - 90;
        let roate_k = k * 360 / 99 - 90;

        //再转换线的长度 1rgb = 129/99 PX
        let len_r = r * 129 / 255;
        let len_g = g * 129 / 255;
        let len_b = b * 129 / 255;


        let ctx = canvas.getContext('2d');
        ctx.strokeStyle = 'white';
        ctx.lineWidth = 6;
        //画第一个圆
        ctx.beginPath();
        ctx.arc(13, 30, 10, -90 * Math.PI / 180, roate_c * Math.PI / 180);
        ctx.stroke();
        ctx.closePath();

        //画第二个圆
        ctx.beginPath();
        ctx.arc(13, 62, 10, -90 * Math.PI / 180, roate_m * Math.PI / 180);
        ctx.stroke();
        ctx.closePath();

        //画第三个圆
        ctx.beginPath();
        ctx.arc(13, 94, 10, -90 * Math.PI / 180, roate_y * Math.PI / 180);
        ctx.stroke();
        ctx.closePath();

        //画第四个圆
        ctx.beginPath();
        ctx.arc(13, 126, 10, -90 * Math.PI / 180, roate_k * Math.PI / 180);
        ctx.stroke();
        ctx.closePath();

        //第一条线
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.moveTo(18, 150);
        ctx.lineTo(18, 150 + len_r);
        ctx.stroke();
        ctx.closePath();

        //第二条线
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.moveTo(21, 150);
        ctx.lineTo(21, 150 + len_g);
        ctx.stroke();
        ctx.closePath();

        //第三条线
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.moveTo(24, 150);
        ctx.lineTo(24, 150 + len_b);
        ctx.stroke();
        ctx.closePath();
    }
}



//颜色卡的类
class card {
    constructor(name, cx16, pinyin, rgb, index) {
        this.name = name
        this.cx16 = cx16
        this.pinyin = pinyin
        this.rgb = rgb
        this.CMYK = RGBtoCMYK(rgb)
        this.index = index + 1
    }

    //创建一个新的li节点
    creatLi() {
        let oli = document.createElement("li");
        let odiv = document.createElement("div");
        let oa = document.createElement("a");
        //点击事件
        oa.onclick = () => {
            changeName(this.name, this.cx16);
            changeValue(this.CMYK, this.cx16);
            document.body.style.background = this.rgb;
        }
        let spans = `<span class="name">${this.name}</span>
                        <span class="pinyin">${this.pinyin}</span>
                        <span class="rgb">${this.cx16}</span>`;
        let ocanvas = document.createElement('canvas');
        ocanvas.width = 50;
        ocanvas.height = 287;
        drawCanvas(this.CMYK, ocanvas);
        oa.innerHTML = spans;
        oa.appendChild(ocanvas);
        odiv.appendChild(oa);
        oli.appendChild(odiv);
        oli.style.top = `${(Math.ceil(this.index/7)-1)*300}px`
        oli.style.left = `${((this.index-1)%7)*65}px`
        oli.style.borderTop = `6px solid  ${this.rgb}`

        //hover事件
        oli.onmouseenter = () => {
            oa.style.opacity = 0.5;
            oa.style.color = this.cx16;

            oli.onmouseleave = function() {
                oa.style.opacity = 1;
                oa.style.color = '#fff';
            }
        }
        return oli;
    }
}


//接受一个数据，里面都是颜色的数据
function createCard(data, place) {
    let obj
    if (place == undefined) {
        obj = document.getElementById("colorBox");
    } else {
        obj = document.getElementById("search_result");
    }

    obj.innerHTML = "";
    data.forEach((item, index) => {
        let ocard = new card(item.name, item.cx16, item.pinyin, item.rgb, index);
        let oli = ocard.creatLi();
        obj.appendChild(oli);
    })
}



function classify(type) {
    $.ajax({
        type: 'GET',
        url: `/loader?type=${type}`,
        success: (data) => {
            if (data) {
                createCard(data)
                return;
            } else {
                classify(type);
            }
        }
    })
}

$("#pullBtn").click(function() {
    let roate; //控制箭头的指向
    let box = $(this).parent();
    let state = $(this).attr("name");
    if (state == 'out') {
        box.css({
            "left": "95%",
            backgroundColor: "transparent"
        });
        $(this).attr("name", "in")
        roate = 90;

    } else {
        box.css({
            "left": "0",
            backgroundColor: "rgba(0,0,0,.7)"
        });
        $(this).attr("name", "out")
        roate = -90;
    }
    //点击就清空所有东西。
    setTimeout(() => {
        $("#search_result").html("");
        $("#search_val").val("");
        $("#pullBtn img").css("transform", `rotate(${roate}deg)`);
    }, 1500);
})

$(".type_nav").on('click', (e) => {
    let ev = e || window.event;
    let target = ev.target || ev.srcElement;

    if (target.nodeName.toLocaleLowerCase() == 'li') {
        classify(target.className);
    }
})

$(".search_btn").on("click", search);
$("#search_val").keydown((e) => {
    e = e || window.event
    if (e.keyCode == 13) {
        search()
    }
})

//搜索事件
function search() {
    let str = {};
    let val = $("#search_val").val();

    if (val.indexOf('#') == -1) {
        $.get(
            "/search", { 'name': val },
            function(data) {

                if (data != undefined) {
                    let newData
                    if (data.length > 7) {
                        newData = data.slice(0, 7)
                    } else {
                        newData = data
                    }
                    createCard(newData, `search_box`)
                    let alis = $("#search_result>li")
                    for (let i = 0; i < newData.length; i++) {
                        alis.eq(i).css("left", 0);
                    }

                } else {

                }


            }
        )
    } else {
        $.get(
            "/search", { "cx16": val },
            function(data) {
                if (data) {
                    let newData
                    if (data.length > 7) {
                        newData = data.slice(0, 7)
                    } else {
                        newData = data
                    }

                    createCard(newData, `search_box`)
                    let alis = $("#search_result>li")
                    for (let i = 0; i < newData.length; i++) {
                        alis.eq(i).css("left", 0);
                    }
                }else{
                    
                }

            }
        )
    }
}